package com.lifeverse.controller;

import com.lifeverse.common.ApiResponse;
import com.lifeverse.entity.Decision;
import com.lifeverse.entity.DecisionFeedback;
import com.lifeverse.entity.DecisionHistory;
import com.lifeverse.entity.enums.DecisionStatus;
import com.lifeverse.entity.enums.DecisionType;
import com.lifeverse.service.DecisionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 决策控制器
 * 提供决策相关的REST API
 */
@Slf4j
@RestController
@RequestMapping("/api/decisions")
@RequiredArgsConstructor
public class DecisionController {
    
    private final DecisionService decisionService;
    
    /**
     * 创建决策
     */
    @PostMapping
    public ApiResponse<Decision> createDecision(@RequestBody CreateDecisionRequest request) {
        try {
            Decision decision = decisionService.createDecision(
                    request.getLifeEntityId(),
                    request.getType(),
                    request.getTitle(),
                    request.getDescription(),
                    request.getContext()
            );
            
            return ApiResponse.success(decision);
        } catch (Exception e) {
            log.error("创建决策失败", e);
            return ApiResponse.error("创建决策失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理决策
     */
    @PostMapping("/{decisionId}/process")
    public ApiResponse<String> processDecision(@PathVariable Long decisionId) {
        try {
            CompletableFuture<Decision> future = decisionService.processDecision(decisionId);
            
            // 异步处理，立即返回
            future.whenComplete((decision, throwable) -> {
                if (throwable != null) {
                    log.error("决策处理失败 - ID: {}", decisionId, throwable);
                } else {
                    log.info("决策处理完成 - ID: {}, 状态: {}", decisionId, decision.getStatus());
                }
            });
            
            return ApiResponse.success("决策处理已启动");
        } catch (Exception e) {
            log.error("启动决策处理失败 - ID: {}", decisionId, e);
            return ApiResponse.error("启动决策处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 执行决策
     */
    @PostMapping("/{decisionId}/execute")
    public ApiResponse<String> executeDecision(@PathVariable Long decisionId) {
        try {
            CompletableFuture<Decision> future = decisionService.executeDecision(decisionId);
            
            // 异步执行，立即返回
            future.whenComplete((decision, throwable) -> {
                if (throwable != null) {
                    log.error("决策执行失败 - ID: {}", decisionId, throwable);
                } else {
                    log.info("决策执行完成 - ID: {}, 状态: {}", decisionId, decision.getStatus());
                }
            });
            
            return ApiResponse.success("决策执行已启动");
        } catch (Exception e) {
            log.error("启动决策执行失败 - ID: {}", decisionId, e);
            return ApiResponse.error("启动决策执行失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取决策详情
     */
    @GetMapping("/{decisionId}")
    public ApiResponse<Decision> getDecision(@PathVariable Long decisionId) {
        try {
            Decision decision = decisionService.getDecision(decisionId);
            return ApiResponse.success(decision);
        } catch (Exception e) {
            log.error("获取决策详情失败 - ID: {}", decisionId, e);
            return ApiResponse.error("获取决策详情失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取生命体的决策列表
     */
    @GetMapping("/life-entity/{lifeEntityId}")
    public ApiResponse<Page<Decision>> getDecisionsByLifeEntity(
            @PathVariable Long lifeEntityId,
            @PageableDefault(size = 20) Pageable pageable) {
        try {
            Page<Decision> decisions = decisionService.getDecisionsByLifeEntity(lifeEntityId, pageable);
            return ApiResponse.success(decisions);
        } catch (Exception e) {
            log.error("获取生命体决策列表失败 - 生命体ID: {}", lifeEntityId, e);
            return ApiResponse.error("获取决策列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取特定状态的决策列表
     */
    @GetMapping("/life-entity/{lifeEntityId}/status/{status}")
    public ApiResponse<Page<Decision>> getDecisionsByStatus(
            @PathVariable Long lifeEntityId,
            @PathVariable DecisionStatus status,
            @PageableDefault(size = 20) Pageable pageable) {
        try {
            Page<Decision> decisions = decisionService.getDecisionsByStatus(lifeEntityId, status, pageable);
            return ApiResponse.success(decisions);
        } catch (Exception e) {
            log.error("获取特定状态决策列表失败 - 生命体ID: {}, 状态: {}", lifeEntityId, status, e);
            return ApiResponse.error("获取决策列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取决策历史
     */
    @GetMapping("/{decisionId}/history")
    public ApiResponse<Page<DecisionHistory>> getDecisionHistory(
            @PathVariable Long decisionId,
            @PageableDefault(size = 20) Pageable pageable) {
        try {
            Page<DecisionHistory> history = decisionService.getDecisionHistory(decisionId, pageable);
            return ApiResponse.success(history);
        } catch (Exception e) {
            log.error("获取决策历史失败 - 决策ID: {}", decisionId, e);
            return ApiResponse.error("获取决策历史失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取决策反馈
     */
    @GetMapping("/{decisionId}/feedback")
    public ApiResponse<Page<DecisionFeedback>> getDecisionFeedback(
            @PathVariable Long decisionId,
            @PageableDefault(size = 20) Pageable pageable) {
        try {
            Page<DecisionFeedback> feedback = decisionService.getDecisionFeedback(decisionId, pageable);
            return ApiResponse.success(feedback);
        } catch (Exception e) {
            log.error("获取决策反馈失败 - 决策ID: {}", decisionId, e);
            return ApiResponse.error("获取决策反馈失败: " + e.getMessage());
        }
    }
    
    /**
     * 添加决策反馈
     */
    @PostMapping("/{decisionId}/feedback")
    public ApiResponse<DecisionFeedback> addDecisionFeedback(
            @PathVariable Long decisionId,
            @RequestBody AddFeedbackRequest request) {
        try {
            DecisionFeedback feedback = decisionService.addDecisionFeedback(
                    decisionId,
                    request.getFeedbackType(),
                    request.getSource(),
                    request.getContent(),
                    request.getRating(),
                    request.getIsPositive()
            );
            
            return ApiResponse.success(feedback);
        } catch (Exception e) {
            log.error("添加决策反馈失败 - 决策ID: {}", decisionId, e);
            return ApiResponse.error("添加决策反馈失败: " + e.getMessage());
        }
    }
    
    /**
     * 取消决策
     */
    @PostMapping("/{decisionId}/cancel")
    public ApiResponse<Decision> cancelDecision(
            @PathVariable Long decisionId,
            @RequestBody CancelDecisionRequest request) {
        try {
            Decision decision = decisionService.cancelDecision(decisionId, request.getReason());
            return ApiResponse.success(decision);
        } catch (Exception e) {
            log.error("取消决策失败 - ID: {}", decisionId, e);
            return ApiResponse.error("取消决策失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取决策统计信息
     */
    @GetMapping("/life-entity/{lifeEntityId}/statistics")
    public ApiResponse<DecisionService.DecisionStatistics> getDecisionStatistics(@PathVariable Long lifeEntityId) {
        try {
            DecisionService.DecisionStatistics statistics = decisionService.getDecisionStatistics(lifeEntityId);
            return ApiResponse.success(statistics);
        } catch (Exception e) {
            log.error("获取决策统计信息失败 - 生命体ID: {}", lifeEntityId, e);
            return ApiResponse.error("获取决策统计信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取活跃决策
     */
    @GetMapping("/active")
    public ApiResponse<List<Decision>> getActiveDecisions() {
        try {
            List<Decision> activeDecisions = decisionService.getActiveDecisions();
            return ApiResponse.success(activeDecisions);
        } catch (Exception e) {
            log.error("获取活跃决策失败", e);
            return ApiResponse.error("获取活跃决策失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取超时决策
     */
    @GetMapping("/timeout")
    public ApiResponse<List<Decision>> getTimeoutDecisions() {
        try {
            List<Decision> timeoutDecisions = decisionService.getTimeoutDecisions();
            return ApiResponse.success(timeoutDecisions);
        } catch (Exception e) {
            log.error("获取超时决策失败", e);
            return ApiResponse.error("获取超时决策失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理超时决策
     */
    @PostMapping("/timeout/handle")
    public ApiResponse<String> handleTimeoutDecisions() {
        try {
            decisionService.handleTimeoutDecisions();
            return ApiResponse.success("超时决策处理完成");
        } catch (Exception e) {
            log.error("处理超时决策失败", e);
            return ApiResponse.error("处理超时决策失败: " + e.getMessage());
        }
    }
    
    // 请求DTO类
    public static class CreateDecisionRequest {
        private Long lifeEntityId;
        private DecisionType type;
        private String title;
        private String description;
        private Map<String, Object> context;
        
        // getters and setters
        public Long getLifeEntityId() { return lifeEntityId; }
        public void setLifeEntityId(Long lifeEntityId) { this.lifeEntityId = lifeEntityId; }
        public DecisionType getType() { return type; }
        public void setType(DecisionType type) { this.type = type; }
        public String getTitle() { return title; }
        public void setTitle(String title) { this.title = title; }
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        public Map<String, Object> getContext() { return context; }
        public void setContext(Map<String, Object> context) { this.context = context; }
    }
    
    public static class AddFeedbackRequest {
        private String feedbackType;
        private String source;
        private String content;
        private BigDecimal rating;
        private Boolean isPositive;
        
        // getters and setters
        public String getFeedbackType() { return feedbackType; }
        public void setFeedbackType(String feedbackType) { this.feedbackType = feedbackType; }
        public String getSource() { return source; }
        public void setSource(String source) { this.source = source; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public BigDecimal getRating() { return rating; }
        public void setRating(BigDecimal rating) { this.rating = rating; }
        public Boolean getIsPositive() { return isPositive; }
        public void setIsPositive(Boolean isPositive) { this.isPositive = isPositive; }
    }
    
    public static class CancelDecisionRequest {
        private String reason;
        
        // getters and setters
        public String getReason() { return reason; }
        public void setReason(String reason) { this.reason = reason; }
    }
}